<template>
  <view class="tiktok-container">
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-item active">关注</view>
      <view class="nav-item">推荐</view>
    </view>
    
    <!-- 内容swiper -->
    <swiper 
      class="content-swiper" 
      :current="currentIndex" 
      @change="onSwiperChange"
      circular
      vertical
      :style="{ height: screenHeight + 'px' }"
    >
      <swiper-item v-for="(item, index) in contentList" :key="index">
        <view class="content-item">
          <!-- 内容展示区 -->
          <view class="content-display">
            <!-- 视频 -->
            <video 
              v-if="item.type === 'video'"
              :src="item.url" 
              :autoplay="currentIndex === index" 
              :loop="true" 
              @play="onMediaPlay(index)"
              @pause="onMediaPause(index)"
              class="media-content"
              :id="'video-' + index"
            ></video>
            
            <!-- 图片组 -->
            <view v-else-if="item.type === 'image' && item.images && item.images.length > 0" class="image-gallery">
              <swiper 
                class="image-swiper" 
                :current="item.currentImageIndex" 
                @change="e => updateImageIndex(item, e.detail.current)"
                :style="{ height: screenHeight + 'px' }"
              >
                <swiper-item v-for="(img, imgIndex) in item.images" :key="imgIndex">
                  <image 
                    :src="img" 
                    mode="aspectFill" 
                    class="gallery-image"
                    @click="previewImages(item, imgIndex)"
                  ></image>
                </swiper-item>
              </swiper>
              <view class="image-indicator" v-if="item.images.length > 1">
                <text>{{item.currentImageIndex + 1}}/{{item.images.length}}</text>
              </view>
            </view>
            
            <!-- 单张图片 -->
            <image 
              v-else-if="item.type === 'image'"
              :src="item.url" 
              mode="aspectFill" 
              class="media-content"
              @click="previewImages(item, 0)"
            ></image>
          </view>
          
          <!-- 内容信息和互动区 -->
          <view class="content-info">
            <!-- 左侧信息 -->
            <view class="left-info">
              <view class="user-info">
                <image class="avatar" :src="item.avatar"></image>
                <view class="user-name">{{item.nickname}}</view>
                <button class="follow-btn">+ 关注</button>
              </view>
              
              <view class="content-desc">{{item.description}}</view>
              
              <!-- 标签 -->
              <view class="tags" v-if="item.tags && item.tags.length > 0">
                <text class="tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">#{{tag}}</text>
              </view>
            </view>
            
            <!-- 右侧互动按钮 -->
            <view class="right-actions">
              <!-- 点赞按钮 -->
              <view class="action-btn" @click.stop="toggleLike(index)">
                <uni-icons 
                  :type="item.isLiked ? 'heart-filled' : 'heart'" 
                  size="36" 
                  :color="item.isLiked ? '#ff2442' : '#fff'"
                ></uni-icons>
                <text class="action-count">{{item.likeCount}}</text>
              </view>
              
              <!-- 评论按钮 -->
              <view class="action-btn" @click.stop="showComments(index)">
                <uni-icons type="chat" size="36" color="#fff"></uni-icons>
                <text class="action-count">{{item.commentCount}}</text>
              </view>
              
              <!-- 分享按钮 -->
              <view class="action-btn">
                <uni-icons type="share" size="36" color="#fff"></uni-icons>
                <text class="action-count">{{item.shareCount}}</text>
              </view>
              
              <!-- 音乐图标 -->
              <view class="music-icon">
                <image class="music-img" :src="item.avatar"></image>
              </view>
            </view>
          </view>
          
          <!-- 评论区 (默认隐藏) -->
          <view class="comments-container" :class="{ 'show': currentActiveComment === index }">
            <view class="comments-header">
              <text class="comments-title">评论区</text>
              <uni-icons type="close" size="24" color="#fff" @click="hideComments"></uni-icons>
            </view>
            
            <scroll-view 
              class="comments-list" 
              scroll-y 
              @scrolltoupper="loadMoreComments"
              :scroll-top="scrollTop"
              :scroll-into-view="scrollIntoView"
            >
              <view class="comment-item" v-for="(comment, idx) in item.comments" :key="idx" :id="'comment-' + idx">
                <image class="comment-avatar" :src="comment.avatar"></image>
                <view class="comment-content">
                  <view class="comment-user">
                    <text class="comment-name">{{comment.nickname}}</text>
                    <text class="comment-time">{{comment.time}}</text>
                  </view>
                  <text class="comment-text">{{comment.content}}</text>
                  <view class="comment-actions">
                    <uni-icons 
                      :type="comment.isLiked ? 'heart-filled' : 'heart'" 
                      size="18" 
                      :color="comment.isLiked ? '#ff2442' : '#888'"
                      @click="toggleCommentLike(comment, idx, index)"
                    ></uni-icons>
                    <text class="like-count">{{comment.likeCount}}</text>
                  </view>
                </view>
              </view>
              
              <!-- 加载更多提示 -->
              <view class="loading-more" v-if="item.loadingComments">
                <text>加载更多评论...</text>
              </view>
            </scroll-view>
            
            <!-- 底部评论输入框 -->
            <view class="comment-input-area">
              <image class="input-avatar" :src="userAvatar"></image>
              <input 
                class="comment-input" 
                placeholder="留下你的精彩评论" 
                v-model="newComment"
                @focus="onInputFocus"
              ></input>
              <button class="send-btn" :disabled="!newComment.trim()" @click="postComment(index)">发送</button>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>
    
    <!-- 加载提示 -->
    <view class="loading-tip" v-if="isLoading">
      <text>加载更多内容中...</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentIndex: 0,
      currentActiveComment: -1,
      newComment: '',
      userAvatar: '/static/default_avatar.jpg',
      contentList: [],
      isLoading: false,
      page: 1,
      hasMore: true,
      screenHeight: 0,
      scrollTop: 0,
      scrollIntoView: ''
    };
  },
  onReady() {
    this.loadInitialData();
  },
  methods: {
    // 初始化加载数据
    loadInitialData() {
      const res = uni.getSystemInfoSync();
      this.screenHeight = res.windowHeight;
      
      this.contentList = this.generateMockData(1, 20);
      this.page = 2;
      
      // 确保第一个视频开始播放
      setTimeout(() => {
        this.playCurrentMedia();
      }, 300);
    },
    
    // 生成模拟数据
    generateMockData(startId, count) {
      const mockData = [];
      for (let i = startId; i < startId + count; i++) {
        const type = i % 3 === 0 ? 'video' : 'image';
        mockData.push({
          id: i,
          type,
          url: type === 'video' ? `https://yc-1334337081.cos.ap-chengdu.myqcloud.com/uploads/images/20250606/c094cb7440015ac442e3c647632c66b1.mp4` : '',
          avatar: `https://picsum.photos/100/100?random=${i}`,
          nickname: `用户${i}`,
          description: `${type === 'video' ? '视频' : '图片'}内容描述 #${i}`,
          tags: ['热门', '推荐', '精选'].slice(0, Math.floor(Math.random() * 3) + 1),
          likeCount: Math.floor(Math.random() * 100000),
          commentCount: Math.floor(Math.random() * 1000),
          shareCount: Math.floor(Math.random() * 1000),
          isLiked: false,
          currentImageIndex: 0,
          images: type === 'image' ? [
            `https://picsum.photos/800/1200?random=${i}`,
            `https://picsum.photos/800/1200?random=${i + 100}`,
            `https://picsum.photos/800/1200?random=${i + 200}`
          ] : [],
          comments: [
            {
              id: i * 100 + 1,
              avatar: `https://picsum.photos/100/100?random=${i * 100 + 1}`,
              nickname: `评论用户${i * 100 + 1}`,
              content: `这是一条精彩的评论 #${i * 100 + 1}`,
              time: '1小时前',
              likeCount: Math.floor(Math.random() * 1000),
              isLiked: false
            },
            {
              id: i * 100 + 2,
              avatar: `https://picsum.photos/100/100?random=${i * 100 + 2}`,
              nickname: `评论用户${i * 100 + 2}`,
              content: `这条${type === 'video' ? '视频' : '图片'}真不错！ #${i * 100 + 2}`,
              time: '2小时前',
              likeCount: Math.floor(Math.random() * 1000),
              isLiked: false
            }
          ],
          loadingComments: false,
          commentsPage: 1,
          hasMoreComments: true
        });
      }
      return mockData;
    },
    
    // swiper切换事件
    onSwiperChange(e) {
      this.currentIndex = e.detail.current;
      this.playCurrentMedia();
      
      // 检查是否需要加载更多内容
      if (this.currentIndex >= this.contentList.length - 3 && this.hasMore && !this.isLoading) {
        this.loadMoreData();
      }
    },
    
    // 播放当前媒体（视频）
    playCurrentMedia() {
      // 暂停所有视频
      for (let i = 0; i < this.contentList.length; i++) {
        const video = document.getElementById(`video-${i}`);
        if (video && i !== this.currentIndex) {
          video.pause();
        }
      }
      
      // 播放当前视频
      const currentItem = this.contentList[this.currentIndex];
      if (currentItem && currentItem.type === 'video') {
        const video = document.getElementById(`video-${this.currentIndex}`);
        if (video) video.play();
      }
    },
    
    // 媒体播放事件
    onMediaPlay(index) {
      // 暂停其他视频
      for (let i = 0; i < this.contentList.length; i++) {
        if (i !== index && this.contentList[i].type === 'video') {
          const video = document.getElementById(`video-${i}`);
          if (video) video.pause();
        }
      }
    },
    
    // 媒体暂停事件
    onMediaPause(index) {
      // 可以添加暂停时的逻辑
    },
    
    // 更新图片索引
    updateImageIndex(item, imgIndex) {
      item.currentImageIndex = imgIndex;
    },
    
    // 预览图片
    previewImages(item, current) {
      const urls = item.images.length > 0 ? item.images : [item.url];
      uni.previewImage({
        urls,
        current: urls[current] || urls[0]
      });
    },
    
    // 显示评论区
    showComments(index) {
      this.currentActiveComment = index;
      
      // 滚动到评论区顶部
      setTimeout(() => {
        const commentsList = this.$refs.commentsList;
        if (commentsList) {
          commentsList.scrollTop = 0;
        }
      }, 300);
    },
    
    // 隐藏评论区
    hideComments() {
      this.currentActiveComment = -1;
    },
    
    // 点赞/取消点赞
    toggleLike(index) {
      const item = this.contentList[index];
      item.isLiked = !item.isLiked;
      
      if (item.isLiked) {
        item.likeCount += 1;
      } else {
        item.likeCount -= 1;
      }
    },
    
    // 评论点赞/取消点赞
    toggleCommentLike(comment, commentIndex, contentIndex) {
      comment.isLiked = !comment.isLiked;
      
      if (comment.isLiked) {
        comment.likeCount += 1;
      } else {
        comment.likeCount -= 1;
      }
    },
    
    // 输入框聚焦
    onInputFocus() {
      // 可以添加输入框聚焦时的逻辑，如调整布局
    },
    
    // 发布评论
    postComment(index) {
      if (!this.newComment.trim()) return;
      
      const newComment = {
        id: Date.now(),
        avatar: this.userAvatar,
        nickname: '当前用户',
        content: this.newComment,
        time: '刚刚',
        likeCount: 0,
        isLiked: false
      };
      
      // 添加到评论列表顶部
      this.contentList[index].comments.unshift(newComment);
      this.contentList[index].commentCount += 1;
      
      // 清空输入框
      this.newComment = '';
      
      // 显示评论成功提示
      uni.showToast({
        title: '评论成功',
        icon: 'success',
        duration: 2000
      });
      
      // 滚动到新评论
      setTimeout(() => {
        const commentsList = this.$refs.commentsList;
        if (commentsList) {
          commentsList.scrollTop = 0;
        }
      }, 500);
    },
    
    // 加载更多评论
    loadMoreComments() {
      const currentItem = this.contentList[this.currentActiveComment];
      if (!currentItem || currentItem.loadingComments || !currentItem.hasMoreComments) return;
      
      currentItem.loadingComments = true;
      
      // 模拟加载评论
      setTimeout(() => {
        const newComments = [
          {
            id: currentItem.comments.length > 0 ? currentItem.comments[0].id + 1 : Date.now(),
            avatar: `https://picsum.photos/100/100?random=${Date.now()}`,
            nickname: `新评论用户${Date.now()}`,
            content: `这是一条新加载的评论 #${Date.now()}`,
            time: '刚刚',
            likeCount: Math.floor(Math.random() * 100),
            isLiked: false
          },
          {
            id: currentItem.comments.length > 0 ? currentItem.comments[0].id + 2 : Date.now() + 1,
            avatar: `https://picsum.photos/100/100?random=${Date.now() + 1}`,
            nickname: `新评论用户${Date.now() + 1}`,
            content: `这也是一条新加载的评论 #${Date.now() + 1}`,
            time: '刚刚',
            likeCount: Math.floor(Math.random() * 100),
            isLiked: false
          }
        ];
        
        currentItem.comments = [...newComments, ...currentItem.comments];
        currentItem.commentCount += newComments.length;
        currentItem.commentsPage++;
        
        // 模拟没有更多评论
        if (currentItem.commentsPage >= 3) {
          currentItem.hasMoreComments = false;
        }
        
        currentItem.loadingComments = false;
        
        // 滚动到新评论
        setTimeout(() => {
          const commentsList = this.$refs.commentsList;
          if (commentsList) {
            commentsList.scrollTop = 0;
          }
        }, 300);
      }, 1500);
    },
    
    // 加载更多内容
    loadMoreData() {
      this.isLoading = true;
      
      // 模拟网络请求延迟
      setTimeout(() => {
        const newData = this.generateMockData(this.page * 10, 10);
        this.contentList = [...this.contentList, ...newData];
        this.page++;
        
        // 模拟没有更多数据的情况
        if (this.page > 5) {
          this.hasMore = false;
        }
        
        this.isLoading = false;
      }, 1000);
    }
  },
  onUnload() {
    // 暂停所有视频
    for (let i = 0; i < this.contentList.length; i++) {
      const video = document.getElementById(`video-${i}`);
      if (video) video.pause();
    }
  }
};
</script>

<style lang="scss" scoped>
.tiktok-container {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #000;
  overflow: hidden;
  z-index: 1000;
  
  // 确保所有内部元素使用盒模型
  * {
    box-sizing: border-box;
  }
}

.top-nav {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 30;
  
  .nav-item {
    color: #fff;
    font-size: 18px;
    padding: 0 40rpx;
    height: 100%;
    display: flex;
    align-items: center;
    position: relative;
    
    &.active::after {
      content: '';
      position: absolute;
      bottom: 10rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 6rpx;
      background-color: #fff;
      border-radius: 3rpx;
    }
  }
}

.content-swiper {
  width: 100%;
  height: 100%;
}

.content-item {
  width: 100%;
  height: 100%;
  position: relative;
  
  .content-display {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
  }
  
  .media-content {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .image-gallery {
    width: 100%;
    height: 100%;
    position: relative;
    
    .image-swiper {
      width: 100%;
      height: 100%;
    }
    
    .gallery-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .image-indicator {
      position: absolute;
      bottom: 20rpx;
      right: 20rpx;
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
      font-size: 14px;
      padding: 4rpx 12rpx;
      border-radius: 16rpx;
      z-index: 5;
    }
  }
  
  .content-info {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 0 30rpx 60rpx;
    box-sizing: border-box;
    z-index: 10;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    height: 100%;
    background: linear-gradient(to top, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0) 60%);
  }
  
  .left-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    
    .user-info {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        border: 2rpx solid #fff;
      }
      
      .user-name {
        color: #fff;
        font-size: 18px;
        margin-right: 20rpx;
        font-weight: 500;
      }
      
      .follow-btn {
        width: 120rpx;
        height: 50rpx;
        line-height: 50rpx;
        background-color: #ff2442;
        color: #fff;
        text-align: center;
        border-radius: 25rpx;
        font-size: 16px;
        border: none;
        padding: 0;
        font-weight: 500;
      }
    }
    
    .content-desc {
      color: #fff;
      font-size: 16px;
      line-height: 1.5;
      margin-bottom: 20rpx;
      max-width: 70%;
      text-shadow: 0 1px 2px rgba(0,0,0,0.5);
    }
    
    .tags {
      display: flex;
      flex-wrap: wrap;
      
      .tag {
        background-color: rgba(255, 255, 255, 0.2);
        color: #fff;
        font-size: 14px;
        padding: 4rpx 16rpx;
        border-radius: 16rpx;
        margin-right: 10rpx;
        margin-bottom: 10rpx;
        text-shadow: 0 1px 1px rgba(0,0,0,0.3);
      }
    }
  }
  
  .right-actions {
    position: absolute;
    bottom: 100rpx;
    right: 30rpx;
    width: 120rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .action-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 30rpx;
      
      .action-count {
        color: #fff;
        font-size: 14px;
        margin-top: 10rpx;
        text-shadow: 0 1px 2px rgba(0,0,0,0.5);
      }
    }
    
    .music-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      border: 2rpx solid rgba(255, 255, 255, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 30rpx;
      
      .music-img {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        animation: rotate 10s linear infinite;
      }
    }
  }
}

// 评论区样式
.comments-container {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 0;
  background-color: rgba(0, 0, 0, 0.9);
  border-radius: 30rpx 30rpx 0 0;
  z-index: 20;
  transition: all 0.3s ease;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  &.show {
    height: 70%;
  }
  
  .comments-header {
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
    
    .comments-title {
      color: #fff;
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .comments-list {
    flex: 1;
    padding: 20rpx 30rpx;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    
    .comment-item {
      display: flex;
      margin-bottom: 30rpx;
      
      .comment-avatar {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }
      
      .comment-content {
        flex: 1;
        
        .comment-user {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;
          
          .comment-name {
            color: #fff;
            font-size: 16px;
            font-weight: 500;
            margin-right: 20rpx;
          }
          
          .comment-time {
            color: #999;
            font-size: 12px;
          }
        }
        
        .comment-text {
          color: #fff;
          font-size: 16px;
          line-height: 1.5;
          margin-bottom: 10rpx;
        }
        
        .comment-actions {
          display: flex;
          align-items: center;
          
          .like-count {
            color: #999;
            font-size: 12px;
            margin-left: 10rpx;
          }
        }
      }
    }
  }
  
  .loading-more {
    text-align: center;
    color: #999;
    padding: 20rpx 0;
  }
  
  .comment-input-area {
    height: 120rpx;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    border-top: 1rpx solid rgba(255, 255, 255, 0.1);
    
    .input-avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }
    
    .comment-input {
      flex: 1;
      height: 80rpx;
      background-color: rgba(255, 255, 255, 0.1);
      border-radius: 40rpx;
      padding: 0 30rpx;
      color: #fff;
      font-size: 16px;
      margin-right: 20rpx;
      border: none;
    }
    
    .send-btn {
      width: 120rpx;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #ff2442;
      color: #fff;
      text-align: center;
      border-radius: 40rpx;
      font-size: 16px;
      border: none;
      
      &[disabled] {
        background-color: rgba(255, 36, 66, 0.5);
      }
    }
  }
}

.loading-tip {
  position: absolute;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  font-size: 14px;
  z-index: 30;
  display: flex;
  align-items: center;
  
  uni-icons {
    margin-right: 10rpx;
  }
}

// 音乐图标旋转动画
@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>